#!/bin/bash -e
#基础变量
#1.项目名全部为中文,需要csv支持utf8
#2.多选框,并发构建,ok
#3.平滑重启 
#4.支持前端删除缓存,ok
#5.支持非root用户更新
#6.通知问题的优化

#编译还是更新
select_name=$1
#项目名
project_name=$2
#admin,core,report.默认值为core
server_name=$3
#环境,test,prod
env_name=$4
try_version=$5
db_select=$6

#是否进行不停机更新
#uptdate_nodown=$8
select_dir=/data
jenkins_dir=$select_dir/jenkins/workspace
#基础代码路径
base_dir=$jenkins_dir/devops
#根据jenkins给的变量去拆分其他变量
env_dir=$base_dir/conf/env
jenkins_shell_dir=$base_dir/jenkins/shell
wethink_envfile=$env_dir/"$env_name"_wethink_env.csv
project_dir=$jenkins_dir/$env_name/"$project_name"_"$server_name"
zip_name="$server_name".zip
#远程发送目录
wethink_project_dir=/data/openresty/wethink

if [[ $env_name == prod  ]];then
   echo "不允许运行生产环境"
   exit
fi
#解决linuxcsv乱码文件
#iconv -f gb18030 -t utf-8 wethink_env_file.csv >xx.csv

#获取代码相关变量代码对应仓库和分支
git_env(){
    tmp_dir=$base_dir/tmp
    mkdir -p $tmp_dir
    cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $4}' >$tmp_dir/"$project_name"_pwd.log
    cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $5}' >$tmp_dir/"$project_name"_branch.log
    dingding_file=$env_dir/dingding.csv
    noticeToken=`grep $project_name $dingding_file |  awk -F ',' '{print $2}'`
    if [[ $noticeToken == ""   ]];then
        noticeToken="https://oapi.dingtalk.com/robot/send?access_token=02fd5264b64d3907ec768ad1b133f739cb5720e7e90148d4e6ca37cf34a83a94"
    fi    
    echo $noticeToken >$tmp_dir/"$project_name"_noticeToken.log
}

#编译相关变量,代码版本
complish_env(){
    if [[ $try_version == NO ]];then
        code_version=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $6}'`
    else
        code_version=$try_version
    fi

    #code_variable=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $7}'`
    if [[ $server_name == core   ]];then
        code_variable="core/wethink-web/target/wethink.war"
        if [[ $project_name == zhjt ]];then
            code_variable="target/report-service-1.0-SNAPSHOT.war"
        fi
    elif [[ $server_name == report ]];then
        code_variable="target/wizbank-report.war"
    else 
        code_variable="dist"
    fi
}

#前端构建函数
front_build(){
    #确定node版本
    export NODE_HOME=/app/$code_version
    export PATH=$NODE_HOME/bin:$PATH
    #判断是否需要删除缓存
    if [[  $try_version != NO  ]];then
        rm -rf node_modules
        npm cache clean --force
    fi
    #构建
    npm install
    npm run build
    mkdir -p $wethink_project_dir/$env_name/$project_name  /app/project/$project_name
    #压缩和传包
    cd $code_variable
    zip -r $zip_name *
    rsync -az $zip_name $wethink_project_dir/$env_name/$project_name/
    mv -f  $zip_name  /app/project/$project_name/
}

#后端构建函数
api_build(){
    #指定java版本
    export JAVA_HOME=/data/$code_version
    export PATH=$JAVA_HOME/bin:$PATH
    export CLASSPATH=.:$JAVA_HOME/jre/lib:$JAVA_HOME/lib:$JAVA_HOME/lib/tools.jar       
    mkdir -p $wethink_project_dir/$env_name/$project_name /app/project/$project_name
    #构建
    if [[ $project_name == wethink180  ]] ||  [[ $project_name == wethink_product ]];then
        mvn clean package -P$db_select -Dmaven.test.skip=true
    else
        mvn clean package -Dmaven.test.skip=true
    fi
    #传包
    rsync -az  $project_dir/$code_variable $wethink_project_dir/$env_name/$project_name/$zip_name
    mv -f  $project_dir/$code_variable /app/project/$project_name/$server_name.zip
}

#根据项目和对应环境赋予对应的变量,ansible替代?
change_ip(){
    net_segment=`echo $target_ip | awk -F '.' '{print $1"."$2"."$3}'`
    login_user=root
    port=xx

    if [[ $net_segment == 192.168.2 ]];then
        gossh="ssh -p$port -i /app/pem/nick.pem -o StrictHostKeyChecking=no $login_user"
        get_ip="http://ip1:port1"
    elif [[  $net_segment == 192.168.4 ]];then
        gossh="ssh -p$port -i /app/pem/nick.pem -o StrictHostKeyChecking=no $login_user"
        get_ip="http://ip1:port1"  
    elif [[  $net_segment == 192.168.3 ]];then
        gossh="ssh -p$port -i /app/pem/nick.pem -o StrictHostKeyChecking=no -J root@14.29.84.165:9981  $login_user"
        get_ip="http://ip2:port2" 
    elif [[  $project_name == xxx ]] && [[ env_name == prod ]] ;then
        login_user=xxx
        gossh="ssh -p$port -i /app/pem/nick.pem -o StrictHostKeyChecking=no $login_user"
    else
        gossh="ssh -p$port -i /app/pem/nick.pem -o StrictHostKeyChecking=no $login_user"
        get_ip="http://ip2:port2"
    fi
    get_shell=$get_ip/remote    
    get_http="$get_ip/wethink/$env_name/$project_name"
}

#更新相关变量
update_env(){
    #环境,目标ip,目标代码目录,进程命令
    # source_env=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $8}'` 
    source_target_ip=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $8}'`
    source_code_dir=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $9}'`
    type_process=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $10}'`
    source_process=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $11}'`
    #远程更新相关变量
    remote_dir=/data/openresty/remote
    update_dir=/app/update/$project_name
    wethink_remote_shell=$remote_dir/wethink_remote.sh
    shell_name=update_"$project_name"_"$server_name".sh
    remote_shell=$remote_dir/$shell_name
    update_shell=$update_dir/$shell_name
}

#远程更新
remote_update(){   
    #下载
    #$gossh@$target_ip "mkdir -p /app/update /app/backup;wget $get_http/$server_name.zip  -q -O $update_dir/$server_name.zip;wget $get_shell/$shell_name -q -O  $update_shell"
    $gossh@$target_ip "mkdir -p $update_dir;wget $get_http/$zip_name  -q -O $update_dir/$zip_name"
    #修改脚本变量,kill进程和传参有冲突
    rsync -az $wethink_remote_shell $remote_shell
    sed -i "s#server_name=xxx#server_name=$server_name#g"               $remote_shell
    sed -i "s#source_code_dir=xxx#source_code_dir=$source_code_dir#g"   $remote_shell
    sed -i "s#type_process=xxx#type_process=$type_process#g"            $remote_shell
    sed -i "s#source_process=xxx#source_process=$source_process#g"      $remote_shell
    sed -i "s#project_name=xxx#project_name=$project_name#g"            $remote_shell
    #远程运行脚本进行备份和更新
    #$gossh@$target_ip "/bin/bash $update_shell"    
    $gossh@$target_ip "curl -Ss $get_ip/remote/$shell_name | bash -x"
    
    #为了安全删除文件
    rm -f $wethink_project_dir/$project_name/$zip_name
}

#nginx平滑重启
#server_name 有点不好判断,现在是通过拷贝文件,缺点修改nginx配置文件,需要同步到其他3个文件
reload_conf(){    
    web_ips=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $11}'`
    nginxconf=`cat $wethink_envfile | awk -F ',' -v project_name=$project_name -v server_name=$server_name '{ if ($2 == project_name && $3 == server_name) print $11}'`
    
    #1.先验证第一台,如果没有问题后面依次平滑重启,如果验证有问题,注释掉第一台,开启后面服务器
    if [[ env_name == gray  ]];then
        gray_nginxconf=xxx
        $gossh@$target_ip "rsync -avz $gray_nginxconf $nginx_conf;$source_process_dir -s reload"
    #3.验证通过,将剩余后端服务器全部重启,然后恢复注释.
    elif [[ env_name == prod  ]];then
        other_nginxconf=xxx
        $gossh@$target_ip "rsync -avz $other_nginxconf $nginx_conf;$source_process_dir -s reload"
    #恢复全部注释
    elif [[ env_name == rollback  ]];then
        rollback_nginxconf=xxx
        $gossh@$target_ip  "rsync -avz $rollback_nginxconf $nginx_conf;$source_process_dir -s reload"
    fi
}

intelligence_publish(){
    ip_num=`echo $source_target_ip | awk -F '|' '{print NF}'`
    for num in `seq 1 $ip_num`
    do
        target_ip=`echo "$source_target_ip" | awk -F '|' '{print $'"$num"'}'`
        change_ip
        remote_update
    done
    #如果执行完对应环境就退出循环
    #break
}

#根据对应变量执行对应函数
case $select_name in
    git)
        git_env
    ;;
    #编译
    complish)
        complish_env
        mkdir -p $wethink_project_dir/$project_name
        cd $project_dir
        case $server_name in
            core)
            api_build  
            ;;
            report)
            api_build  
            ;;
            admin)
                #180变了
                if [[ $project_name == wethink180  ]];then
                    front_build 
                else
                    cd core/wethink-webapp
                    front_build 
                fi
            ;;
            web)
                front_build 
            ;;
            mobile)
                front_build 
            ;;
            *)
                echo "core,report,web,admin,mobile"
            ;;
        esac
    ;;
    #更新
    update)
        #是否进行不停机更新
        if [[  $uptdate_nodown == YES  ]];then
            reload_conf
            update_env
            intelligence_publish
        #rollback环境只进行恢复操作    
        elif [[ env_name == rollback  ]];then
            reload_conf
        else
            update_env
            intelligence_publish
        fi
    ;;
    *)
        echo "git,complish,update"
    ;;
esac